import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import { getRouterApi } from "@/http/api";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus";


import Customer from '../views/customer/index.vue'

const routes: RouteRecordRaw[] = [
    {
        path:'/customer',
        name:'customer',
        component:Customer
    },
    {
        path: '/',
        // component: () => import("../views/login/index.vue"),
        redirect: '/index'
    },
    {
        path: '/',
        component: () => import("../views/home/index.vue"),
        children: [
            { path: 'index', name: 'index', component: () => import("../views/index/index.vue") }
        ]
    },
    {
        path: '/login',
        component: () => import("../views/login/index.vue")
    },

]

const router = createRouter({
    routes,
    history: createWebHashHistory(),
})

router.beforeEach((to, from, next) => {
    const store = useUserStore();
    //前提是判断是否存在token，不存在则需要拿token
    let token = localStorage.getItem("token")
    //每个页面都要进行权限判断，判断是否存在数据，没有就需要发起请求
    if (store.menus.length === 0 && token) {
        getRouterApi().then(res => {
            if (res.code === 200) {
                // console.log(store.username);
                store.menus = res.data;
                res.data.splice(res.data.length - 1, 1);
                store.menus.forEach((item: any) => {
                    const route: RouteRecordRaw = {

                        path: item.path,
                        name: item.name,
                        component: () => import("../views/home/index.vue"),
                        meta: item.meta,

                        children: item.children.map((Uitem: any) => ({
                            path: item.path + "/" + Uitem.path,
                            name: Uitem.name,
                            component: () => import(`../views/${item.name}/${Uitem.name}.vue`),
                            meta: Uitem.meta
                        }))

                    }
                    // if (item.children[0]) {
                    //     route.redirect = `/${item.name}/${p.children[0]?.name}`
                    // }
                    // console.log(router.getRoutes(), "查看现有路由");
                    router.addRoute(route)
                })
                next(to.fullPath);
            }
        });
        //判断有无token,如果没有token，并且访问的不是 login就跳转回login
    } else if (!token && to.path !== '/login') {
        ElMessage.error("请先登录")
        next('/login')
    }
    //如果已经登录了，不能回到登陆页面
    else if (token && store.menus.length !== 0 && to.path === "/login") {
        ElMessage.warning("请先退出登录再重新登录");
        //不让用户访问登录页,跳转回原来的页面
        next(from.fullPath);
    }
    else {
        next();
    }

})

export default router;